<template>
  <el-form ref="formRef" :model="form" label-width="auto" class="form-container" :rules="rules" size="default">
    <el-form-item label="客户姓名" prop="customerId" required>
      <!-- Show text input when in edit mode -->
      <el-input v-model="form.customerName" v-if="isEditMode" disabled />
      <!-- Show select dropdown when in add mode -->
      <el-select v-else v-model="form.customerId" filterable clearable placeholder="请选择客户" style="width: 100%"
                 :loading="loading">
        <el-option v-for="customer in customerAllName" :key="customer.customerId" :label="customer.customerName"
                   :value="customer.customerId" />
        <template #empty>
          <el-empty description="暂无客户数据" v-if="!loading" />
        </template>
      </el-select>
    </el-form-item>

    <el-form-item label="退住时间" prop="retreattime" required>
      <div class="block">
        <el-date-picker v-model="form.retreattime" type="date" placeholder="请选择退住时间" style="width: 100%"
                        value-format="YYYY-MM-DD" format="YYYY-MM-DD" />
      </div>
    </el-form-item>
    <el-form-item label="退住类型" prop="retreattype" required>
      <el-select v-model="form.retreattype" clearable placeholder="请选择退住类型" style="width: 100%">
        <el-option v-for="item in retreattype" :key="item.value" :label="item.label" :value="item.value" />
      </el-select>
    </el-form-item>
    <el-form-item label="退住原因" prop="retreatreason" required>
      <el-input v-model="form.retreatreason" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit">保存</el-button>
      <el-button @click="cancleEdit">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script setup name='edit'>
import { ref, computed } from "vue";
import { saveOrUpdate, getById, getCustomerWithoutBack, getCustomersName } from "@/api/customer/backdown/index.js";
import { ElNotification } from 'element-plus'
import { onMounted } from "vue";

// 表单信息
const form = ref({
  customerId: '',
  customerName: '',
  retreattime: '',
  retreattype: '',
  retreatreason: '',
})

// 代表父组件传过来的closeEdit函数
const { closeEdit, editId } = defineProps(['closeEdit', 'editId'])

const loading = ref(false)
// 创建引用 用于表单必选项验证
const formRef = ref()
// 用于添加客户外出的姓名下拉选
const customerAllName = ref();

// 判断是否是编辑模式
const isEditMode = computed(() => {
  return editId && editId !== 0;
});

// 获取没有退住记录的客户列表
async function customerNameList() {
  loading.value = true
  try {
    // 修改为调用没有退住记录的接口  
    // 这里有问题 使用 getCustomerWithoutBack 会导致修改的时候无法显示客户姓名 因为只查询到未添加的客户姓名了
    //           使用 getCustomersName 会导致添加时下拉选时全部人员
    const response = isEditMode.value ? await getCustomersName() : await getCustomerWithoutBack();
    customerAllName.value = response
  } catch (e) {
    console.error("查询失败:", e)
  } finally {
    loading.value = false
  }
}

// 表单验证必选项规则
const onSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      console.log("form.value:", form.value);
      saveOrUpdate(form.value).then(success => {
        ElNotification({
          title: '消息',
          type: 'success',
          message: "保存成功",
        })
        closeEdit(true);
      })
    } else {
      ElNotification({
        title: '错误',
        type: 'error',
        message: '请填写所有必填项',
      })
      return false
    }
  })
}

// 点击取消按钮
const cancleEdit = () => {
  closeEdit(false);
}

// 当修改操作的到时候 根据主键查询
const pageGetById = async () => {
  try {
    const user = await getById(editId);
    if (user) {
      form.value = {
        ...user,
        // 确保retreattype是字符串类型，与选项的value类型一致
        retreattype: user.retreattype.toString()
      };
    } else {
      console.warn("未找到id");
    }
  } catch (error) {
    console.error("获取数据失败:", error);
  }
}

// 表单验证规则 必选项
const rules = {
  customerId: [{ required: true, message: '请选择客户姓名', trigger: 'blur' },],
  retreattime: [{ required: true, message: '请选择退住时间', trigger: 'blur' },],
  retreattype: [{ required: true, message: '请选择退住类型', trigger: 'change' },],
  retreatreason: [{ required: true, message: '请输入退住原因', trigger: 'change' },]
}

// 退住类型选项
const retreattype = [
  { value: '0', label: '正常退住' },
  { value: '1', label: '死亡退住' },
  { value: '2', label: '保留床位' }
]

onMounted(() => {
  customerNameList();
  if (editId) {
    pageGetById()
  }
})
</script>

<style scoped>
.form-container {
  width: 300px;
  justify-content: center;
  align-items: center;
  padding-left: 25px;
}
</style>